package com.example.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.entity.FileNode;

import com.example.entity.Result;
import com.example.service.FileNodeService;

import com.example.service.FileService;
import com.example.utils.ResultUtil;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 *
 */
@RestController
@RequestMapping("/fileNode")
public class FileNodeController {
    @Autowired
    FileService fileService;
    @Autowired
    FileNodeService fileNodeService;
    @PostMapping("/insert")
    public Result insert(MultipartFile file, @NotNull @Validated FileNode fileNode) {

        JSONObject jsonObject = fileNodeService.insert(file, fileNode);
        FileNode newFileNode = (FileNode)jsonObject.get("data");
        return  ResultUtil.success(newFileNode);
    }
    @PostMapping("/update")
    public Result update(MultipartFile file, @NotNull @Validated FileNode fileNode) {
        JSONObject jsonObject = fileNodeService.update(file, fileNode);
        FileNode newFileNode = (FileNode) jsonObject.get("data");
        return ResultUtil.success(newFileNode);
    }

    @PostMapping("/updateProperty")
    public Result updateProperty(@RequestBody FileNode fileNode) {
        JSONObject jsonObject = fileNodeService.updateProperty(fileNode);
        FileNode newFileNode = (FileNode) jsonObject.get("data");
        return ResultUtil.success(newFileNode);
    }

    @PostMapping("/deleteById")
    public Result deleteById(@RequestBody FileNode fileNode) {
        JSONObject jsonObject = fileNodeService.deleteById(fileNode);
        String msg = (String) jsonObject.get("msg");
        if (msg.equals("success")) {
            return ResultUtil.success(msg);
        }
        return ResultUtil.error(500, msg);
    }

    @PostMapping("/deleteFile")
    public Result deleteFile(@RequestBody FileNode fileNode) {
        JSONObject jsonObject = fileNodeService.deleteFile(fileNode);
        String msg = (String) jsonObject.get("msg");
        if (msg.equals("success")) {
            return ResultUtil.success(msg);
        }
        return ResultUtil.error(500, msg);
    }

    @GetMapping("/selectAll")
    public Result selectAll(FileNode fileNode) {
        fileNode.setHasParent(null);
        fileNode.setHasChild(null);
        JSONObject jsonObject = fileNodeService.selectAll(fileNode);
        List<FileNode> fileNodeList = (List<FileNode>)jsonObject.get("data");
        return ResultUtil.success(fileNodeList);
    }

    @GetMapping("/selectOneById")
    public Result selectOneById(Long id) {
        JSONObject jsonObject = fileNodeService.selectOneById(id);
        FileNode fileNode = (FileNode)jsonObject.get("data");
        return ResultUtil.success(fileNode);
    }
}
